package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/esapi"
	"log"
	"strconv"
	"strings"
	"sync"
	"time"
	"week2a/models/global"
	"week2a/models/mysql"
	"week2a/types"
)

var wg sync.WaitGroup

// 定时执行同步
func SyncTime() *time.Timer {
	newnow := time.Now()

	timedate := time.Date(newnow.Year(), newnow.Month(), newnow.Day(), 12, 0, 0, 0, time.Local)

	if timedate.After(newnow) {
		timedate = timedate.Add(20 * time.Hour)
	}
	sub := timedate.Sub(newnow)

	timer := time.NewTimer(sub)
	return timer
}

func SyncVideoEs() {
	//查询mysql 的数据
	list := mysql.GetVideoList()
	//循环列表
	for _, v := range list {
		wg.Add(1)
		vs := v
		syncTime := SyncTime()

		<-syncTime.C

		go func(vs mysql.VideoWeek2) {
			defer wg.Done()
			marshal, _ := json.Marshal(vs)
			// Set up the request object directly.
			req := esapi.IndexRequest{
				Index:      "video",
				DocumentID: strconv.Itoa(int(vs.ID)),
				Body:       strings.NewReader(string(marshal)),
				Refresh:    "true",
			}
			// Perform the request with the client.
			res, err := req.Do(context.Background(), global.EsDB)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

			if res.IsError() {
				log.Printf("[%s] Error indexing document ID=%d", res.Status(), vs.ID)
			} else {
				// Deserialize the response into a map.
				var r map[string]interface{}
				if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
					log.Printf("Error parsing the response body: %s", err)
				} else {
					// Print the response status and indexed document version.
					log.Printf("[%s] %s; version=%d", res.Status(), r["result"], int(r["_version"].(float64)))
				}
			}
		}(vs)
	}
	wg.Wait()

	log.Println(strings.Repeat("-", 37))
}

// 高亮
func HighlightVideoEs(videoTitle string, VideoStatus int) types.EsVideoRequest {
	es := global.EsDB

	video := map[string]interface{}{
		"query": map[string]interface{}{
			"bool": map[string]interface{}{
				"must": []map[string]interface{}{
					{"match": map[string]string{"VideoTitle": videoTitle}},
					{"match": map[string]int{"VideoStatus": VideoStatus}},
				},
			},
		},
		"highlight": map[string]interface{}{
			"fields": map[string]interface{}{
				"VideoTitle": map[string]interface{}{
					"pre_tags":  []string{"<em>"},
					"post_tags": []string{"</em>"},
				},
			},
		},
	}

	marshal, _ := json.Marshal(video)

	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("video"),
		es.Search.WithBody(strings.NewReader(string(marshal))),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	defer res.Body.Close()
	fmt.Println("查询结果：：：", res)

	var videoData types.EsVideoRequest
	json.NewDecoder(res.Body).Decode(&videoData)

	return videoData
}
